package com.uhu.code;

import java.util.*;

/**
 * 15. 三数之和
 * https://leetcode.cn/problems/3sum/description/?envType=study-plan-v2&envId=top-100-liked
 */
public class Solution15 {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Map<String, List<Integer>> map = new HashMap<>();
        Arrays.sort(nums);
        int i = 0;
        while (i < nums.length - 2 && nums[i] <= 0) {
            int j = i+1;
            int k = nums.length - 1;
            while(j < k) {
                if(nums[i] + nums[j] + nums[k] == 0) {
                    List<Integer> tl = new ArrayList<>();
                    tl.add(nums[i]);
                    tl.add(nums[j]);
                    tl.add(nums[k]);
                    map.put(""+nums[i]+nums[j]+nums[k], tl);
                    j++;
                }else if(nums[i] + nums[j] + nums[k] < 0){
                    j++;
                }else if(nums[i] + nums[j] + nums[k] > 0) {
                    k--;
                }
            }
            i++;
        }
        result.addAll(map.values());
        return result;
    }
}
